<template>
  <div>
    <a-checkbox-group v-model:value="selectedValue" style="width: 100%" class="items" @change="handleChange">
      <a-checkbox :value="item" :class="idx !== index && isMutex ? 'triangle' : ''" v-for="(item, index) in values" :key="index">
        {{ labels[index] }}
        <a-tooltip placement="top" v-if="tips[index]">
          <template #title>
            <span v-html="tips[index]"></span>
          </template>
          <question-circle-outlined />
        </a-tooltip>
      </a-checkbox>
    </a-checkbox-group>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";
import { QuestionCircleOutlined } from "@ant-design/icons-vue";

const { modelValue, values, labels, tips, isMutex, isLeast, idx } = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  values: {
    type: Array,
    default: () => [],
  },
  labels: {
    type: Array,
    default: () => [],
  },
  tips: {
    type: Array,
    default: () => [],
  },
  // 是否互斥
  isMutex: {
    type: Boolean,
    default: false,
  },
  // 是否最少选中一个
  isLeast: {
    type: Boolean,
    default: false,
  },
  // 互斥的索引
  idx: {
    type: Number,
    default: 0,
  },
});

const selectedValue = ref([...modelValue]);

const mutexVal = values[idx];

const emit = defineEmits(["update:modelValue"]);
const handleChange = (a: []) => {
  if (isMutex) {
    if (a.length === 0 || a[a.length - 1] === mutexVal) {
      selectedValue.value = [mutexVal];
    } else {
      selectedValue.value = a.filter((item) => item !== mutexVal);
    }
  }
};

watch(selectedValue, (newVal, oldVal) => {
  if (isLeast && newVal.length === 0) {
    selectedValue.value = oldVal;
  }
  if (newVal !== oldVal) {
    emit("update:modelValue", newVal);
  }
});
</script>

<style scoped lang="less">
.items {
  .ant-checkbox-wrapper {
    border: 1px solid #c9cdd4;
    padding: 5px;
  }

  .ant-checkbox-wrapper-checked {
    border-color: #23c343;
    color: #05b44b;
    background-color: #e5feef;
  }

  .ant-checkbox-wrapper + .ant-checkbox-wrapper {
    margin-left: 0;
  }

  .ant-checkbox-wrapper {
    :deep(.ant-checkbox) {
      display: none !important;
    }
  }

  .triangle {
    position: relative;
  }

  .triangle::after {
    position: absolute;
    top: 0;
    right: 0;
    width: 0;
    height: 0;
    border: 5px solid transparent;
    border-right: 5px solid rgb(66, 163, 66);
    border-top: 5px solid rgb(66, 163, 66);
  }
}
</style>
